var express = require('express');
var router = express.Router();
var db = require("../model/db");

//查询所有订单
router.get("/all", async function (req, res) {
    if (!req.query.field) {
        req.query.field = "_id";//默认按照_id排序
    }
    if (!req.query.sort) {
        req.query.sort = "asc";//默认按照升序排序
    }
    //拼接排序字符串
    let s = req.query.field;
    if (req.query.sort === "desc") {
        s = "-" + s;
    }
    //处理分页
    if (!req.query.page) {
        req.query.page = 1;//页索引默认为1
    }
    if (!req.query.limit) {
        req.query.limit = 10;//页容量默认为10
    }
    const page = parseInt(req.query.page);
    const limit = parseInt(req.query.limit);
    let condition = {};
    if (req.query.key) {
        const exp = new RegExp(req.query.key, "i")//不区分大小写，模糊查询的正则表达式
        condition = {
            $or: [
                { name: { $regex: exp } },
                { price: { $regex: exp } }
            ]
        };
    }
    const data = await db.Order.find(condition).sort(s).skip((page - 1) * limit).limit(limit);//按照课时升序排序(降序sort("-hours"))
    const count = await db.Order.countDocuments(condition);
    res.send({
        code: 0,
        message: "",
        count,
        data
    });
})
//修改订单
router.put("/:id", async function (req, res) {
    const data = await db.Order.updateOne({ _id: req.params.id }, req.body);
    res.send(
        {
            code: "",    //错误码
            msg: "",     //错误消息体
            data: true  //返回数据
        }
    );
})
//添加订单
router.post("/add", async function (req, res) {
    const data = await db.Order.create(req.body);
    res.send(
        {
            code: "",    //错误码
            msg: "",     //错误消息体
            data //返回数据
        }
    );
})
//得到单个订单
router.get("/:id", async function (req, res) {
    const data = await db.Order.findById(req.params.id);
    res.send(
        {
            code: "",    //错误码
            msg: "",     //错误消息体
            data //返回数据
        }
    )
})
//删除订单
router.delete("/:id",async function(req,res){
    const data = await db.Order.deleteOne({ _id: req.params.id });
    res.send(
        {
            code: "",    //错误码
            msg: "",     //错误消息体
            data: true  //返回数据
        }
    );
})
module.exports = router;